package io.github.siltal.examsystembackend.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.siltal.examsystembackend.dto.ExamHistoryQO;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.io.IOException;
import java.util.List;

// @Converter 注解让 JPA 能够发现这个转换器
@Converter
public class QuestionListConverter implements AttributeConverter<List<ExamHistoryQO>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 将 List<ExamHistoryQO> 转换成 String (用于写入数据库)
    @Override
    public String convertToDatabaseColumn(List<ExamHistoryQO> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            // 在实际应用中，这里应该记录日志
            throw new IllegalArgumentException("Error converting list to JSON", e);
        }
    }

    // 将 String 从数据库读出时，转换成 List<ExamHistoryQO>
    @Override
    public List<ExamHistoryQO> convertToEntityAttribute(String dbData) {
        if (dbData == null || dbData.isBlank()) {
            return null;
        }
        try {
            // 使用 TypeReference 来帮助 Jackson 正确反序列化泛型列表
            return objectMapper.readValue(dbData, new TypeReference<List<ExamHistoryQO>>() {});
        } catch (IOException e) {
            // 记录日志
            throw new IllegalArgumentException("Error converting JSON to list", e);
        }
    }
}